<?php
/**
 * @author 595949289@qq.com
 * @date 2024/12/31 22:22
 */

namespace CuiFox\yii\rbac;

use Yii;
use yii\db\Query;
use yii\rbac\Item;
use yii\rbac\Permission;
use yii\rbac\Role;
use yii\db\Expression;
use yii\rbac\Assignment;
use yii\caching\CacheInterface;
use yii\base\InvalidArgumentException;
use yii\base\InvalidCallException;

class DbManager extends \yii\rbac\DbManager
{
    public $appId;

    public function init()
    {
        parent::init();
        if (!$this->appId) {
            $this->appId = Yii::$app->id;
        }
    }

    /**
     * @param int|string $user
     * @param string $itemName
     * @param array $params
     * @param \yii\rbac\Assignment[] $assignments
     * @return bool
     * @throws \yii\base\InvalidConfigException
     */
    protected function checkAccessRecursive($user, $itemName, $params, $assignments)
    {
        if (($item = $this->getItem($itemName)) === null) {
            return false;
        }

        Yii::debug($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);

        if (!$this->executeRule($user, $item, $params)) {
            return false;
        }

        if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
            return true;
        }

        $query = new Query();
        $parents = $query->select(['parent'])->from($this->itemChildTable)->where([
            'app_id' => $this->appId,
            'child' => $itemName,
        ])->column($this->db);
        foreach ($parents as $parent) {
            if ($this->checkAccessRecursive($user, $parent, $params, $assignments)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param string $name
     * @return null|\yii\rbac\Item
     */
    protected function getItem($name)
    {
        if (empty($name)) {
            return null;
        }

        if (!empty($this->items[$name])) {
            return $this->items[$name];
        }

        $row = (new Query())->from($this->itemTable)->where([
            'app_id' => $this->appId,
            'name' => $name,
        ])->one($this->db);

        if ($row === false) {
            return null;
        }

        return $this->populateItem($row);
    }

    /**
     * @param \yii\rbac\Item $item
     * @return bool
     * @throws \yii\db\Exception
     */
    protected function addItem($item)
    {
        $time = time();
        if ($item->createdAt === null) {
            $item->createdAt = $time;
        }
        if ($item->updatedAt === null) {
            $item->updatedAt = $time;
        }
        $this->db->createCommand()->insert($this->itemTable, [
            'app_id' => $this->appId,
            'name' => $item->name,
            'type' => $item->type,
            'description' => $item->description,
            'rule_name' => $item->ruleName,
            'data' => $item->data === null ? null : serialize($item->data),
            'created_at' => $item->createdAt,
            'updated_at' => $item->updatedAt,
        ])->execute();

        $this->invalidateCache();

        return true;
    }

    /**
     * @param \yii\rbac\Item $item
     * @return bool
     * @throws \yii\db\Exception
     */
    protected function removeItem($item)
    {
        if (!$this->supportsCascadeUpdate()) {
            $this->db->createCommand()->delete($this->itemChildTable, [
                'or',
                ['and', ['app_id' => $this->appId], '[[parent]]=:parent'],
                ['and', ['app_id' => $this->appId], '[[child]]=:child'],
            ], [
                ':parent' => $item->name,
                ':child' => $item->name,
            ])->execute();
            $this->db->createCommand()->delete($this->assignmentTable, [
                'app_id' => $this->appId,
                'item_name' => $item->name,
            ])->execute();
        }

        $this->db->createCommand()->delete($this->itemTable, [
            'app_id' => $this->appId,
            'name' => $item->name,
        ])->execute();

        $this->invalidateCache();

        return true;
    }

    /**
     * @param string $name
     * @param \yii\rbac\Item $item
     * @return bool
     * @throws \yii\db\Exception
     */
    protected function updateItem($name, $item)
    {
        if ($item->name !== $name && !$this->supportsCascadeUpdate()) {
            $this->db->createCommand()->update($this->itemChildTable, ['parent' => $item->name,], [
                'app_id' => $this->appId,
                'parent' => $name,
            ])->execute();
            $this->db->createCommand()->update($this->itemChildTable, ['child' => $item->name], [
                'app_id' => $this->appId,
                'child' => $name,
            ])->execute();
            $this->db->createCommand()->update($this->assignmentTable, ['item_name' => $item->name], [
                'app_id' => $this->appId,
                'item_name' => $name,
            ])->execute();
        }

        $item->updatedAt = time();

        $this->db->createCommand()->update($this->itemTable, [
            'name' => $item->name,
            'description' => $item->description,
            'rule_name' => $item->ruleName,
            'data' => $item->data === null ? null : serialize($item->data),
            'updated_at' => $item->updatedAt,
        ], [
            'app_id' => $this->appId,
            'name' => $name,
        ])->execute();

        $this->invalidateCache();

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function addRule($rule)
    {
        $time = time();
        if ($rule->createdAt === null) {
            $rule->createdAt = $time;
        }
        if ($rule->updatedAt === null) {
            $rule->updatedAt = $time;
        }
        $this->db->createCommand()->insert($this->ruleTable, [
            'app_id' => $this->appId,
            'name' => $rule->name,
            'data' => serialize($rule),
            'created_at' => $rule->createdAt,
            'updated_at' => $rule->updatedAt,
        ])->execute();

        $this->invalidateCache();

        return true;
    }


    /**
     * {@inheritdoc}
     */
    protected function updateRule($name, $rule)
    {
        if ($rule->name !== $name) {
            $this->db->createCommand()->update($this->itemTable, ['rule_name' => $rule->name], [
                'app_id' => $this->appId,
                'rule_name' => $name,
            ])->execute();
        }

        $rule->updatedAt = time();

        $this->db->createCommand()->update($this->ruleTable, [
            'name' => $rule->name,
            'data' => serialize($rule),
            'updated_at' => $rule->updatedAt,
        ], [
            'app_id' => $this->appId,
            'name' => $name,
        ])->execute();

        $this->invalidateCache();

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function removeRule($rule)
    {
        $this->db->createCommand()->update($this->itemTable, ['rule_name' => null], [
            'app_id' => $this->appId,
            'rule_name' => $rule->name,
        ])->execute();

        $this->db->createCommand()->delete($this->ruleTable, [
            'app_id' => $this->appId,
            'name' => $rule->name,
        ])->execute();

        $this->invalidateCache();

        return true;
    }

    /**
     * @param int $type
     * @return array|\yii\rbac\Item[]
     */
    protected function getItems($type)
    {
        $query = (new Query())->from($this->itemTable)->where([
            'app_id' => $this->appId,
            'type' => $type,
        ]);

        $items = [];
        foreach ($query->all($this->db) as $row) {
            $items[$row['name']] = $this->populateItem($row);
        }

        return $items;
    }

    /**
     * @param int|string $userId
     * @return array|mixed|Role[]
     */
    public function getRolesByUser($userId)
    {
        if ($this->isEmptyUserId($userId)) {
            return [];
        }

        if ($this->cache !== null) {
            $data = $this->cache->get($this->getUserRolesCacheKey($userId));

            if ($data !== false) {
                return $data;
            }
        }

        $query = (new Query())->select('b.*')
            ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
            ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
            ->andWhere('{{a}}.[[app_id]]={{b}}.[[app_id]]')
            ->andWhere(['a.user_id' => (string)$userId])
            ->andWhere(['b.type' => Item::TYPE_ROLE])
            ->andWhere(['a.app_id' => $this->appId]);

        $roles = $this->getDefaultRoleInstances();
        foreach ($query->all($this->db) as $row) {
            $roles[$row['name']] = $this->populateItem($row);
        }

        if ($this->cache !== null) {
            $this->cacheUserRolesData($userId, $roles);
        }

        return $roles;
    }

    /**
     * @param string $roleName
     * @return array|\yii\rbac\Permission[]
     */
    public function getPermissionsByRole($roleName)
    {
        $childrenList = $this->getChildrenList();
        $result = [];
        $this->getChildrenRecursive($roleName, $childrenList, $result);
        if (empty($result)) {
            return [];
        }
        $query = (new Query())->from($this->itemTable)->where([
            'app_id' => $this->appId,
            'type' => Item::TYPE_PERMISSION,
            'name' => array_keys($result),
        ]);
        $permissions = [];
        foreach ($query->all($this->db) as $row) {
            $permissions[$row['name']] = $this->populateItem($row);
        }

        return $permissions;
    }

    /**
     * @param int|string $userId
     * @return array|\yii\rbac\Permission[]
     */
    protected function getDirectPermissionsByUser($userId)
    {
        $query = (new Query())->select('b.*')
            ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
            ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
            ->andWhere('{{a}}.[[app_id]]={{b}}.[[app_id]]')
            ->andWhere(['a.user_id' => (string)$userId])
            ->andWhere(['b.type' => Item::TYPE_PERMISSION])
            ->andWhere(['b.app_id' => $this->appId]);

        $permissions = [];
        foreach ($query->all($this->db) as $row) {
            $permissions[$row['name']] = $this->populateItem($row);
        }

        return $permissions;
    }

    /**
     * @param int|string $userId
     * @return array|\yii\rbac\Permission[]
     */
    protected function getInheritedPermissionsByUser($userId)
    {
        $query = (new Query())->select('item_name')
            ->from($this->assignmentTable)
            ->where(['app_id' => $this->appId, 'user_id' => (string)$userId]);

        $childrenList = $this->getChildrenList();
        $result = [];
        foreach ($query->column($this->db) as $roleName) {
            $this->getChildrenRecursive($roleName, $childrenList, $result);
        }

        if (empty($result)) {
            return [];
        }

        $query = (new Query())->from($this->itemTable)->where([
            'app_id' => $this->appId,
            'type' => Item::TYPE_PERMISSION,
            'name' => array_keys($result),
        ]);
        $permissions = [];
        foreach ($query->all($this->db) as $row) {
            $permissions[$row['name']] = $this->populateItem($row);
        }

        return $permissions;
    }

    /**
     * @return array
     */
    protected function getChildrenList()
    {
        $query = (new Query())->from($this->itemChildTable)->where(['app_id' => $this->appId]);
        $parents = [];
        foreach ($query->all($this->db) as $row) {
            $parents[$row['parent']][] = $row['child'];
        }

        return $parents;
    }

    /**
     * @param string $name
     * @return mixed|null|\yii\rbac\Rule
     */
    public function getRule($name)
    {
        if ($this->rules !== null) {
            return isset($this->rules[$name]) ? $this->rules[$name] : null;
        }

        $row = (new Query())->select(['data'])
            ->from($this->ruleTable)
            ->where(['app_id' => $this->appId, 'name' => $name])
            ->one($this->db);
        if ($row === false) {
            return null;
        }
        $data = $row['data'];
        if (is_resource($data)) {
            $data = stream_get_contents($data);
        }
        if (!$data) {
            return null;
        }
        return unserialize($data);
    }

    /**
     * @return array|\yii\rbac\Rule[]
     */
    public function getRules()
    {
        if ($this->rules !== null) {
            return $this->rules;
        }

        $query = (new Query())->from($this->ruleTable)->where(['app_id' => $this->appId]);

        $rules = [];
        foreach ($query->all($this->db) as $row) {
            $data = $row['data'];
            if (is_resource($data)) {
                $data = stream_get_contents($data);
            }
            if ($data) {
                $rules[$row['name']] = unserialize($data);
            }
        }

        return $rules;
    }

    /**
     * @param string $roleName
     * @param int|string $userId
     * @return null|Assignment
     */
    public function getAssignment($roleName, $userId)
    {
        if ($this->isEmptyUserId($userId)) {
            return null;
        }

        $row = (new Query())->from($this->assignmentTable)->where([
            'app_id' => $this->appId,
            'user_id' => (string)$userId,
            'item_name' => $roleName,
        ])->one($this->db);

        if ($row === false) {
            return null;
        }

        return new Assignment([
            'userId' => $row['user_id'],
            'roleName' => $row['item_name'],
            'createdAt' => $row['created_at'],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getAssignments($userId)
    {
        if ($this->isEmptyUserId($userId)) {
            return [];
        }

        $query = (new Query())->from($this->assignmentTable)->where([
            'app_id' => $this->appId,
            'user_id' => (string)$userId,
        ]);

        $assignments = [];
        foreach ($query->all($this->db) as $row) {
            $assignments[$row['item_name']] = new Assignment([
                'userId' => $row['user_id'],
                'roleName' => $row['item_name'],
                'createdAt' => $row['created_at'],
            ]);
        }

        return $assignments;
    }

    public function addChild($parent, $child)
    {
        if ($parent->name === $child->name) {
            throw new InvalidArgumentException("Cannot add '{$parent->name}' as a child of itself.");
        }

        if ($parent instanceof Permission && $child instanceof Role) {
            throw new InvalidArgumentException('Cannot add a role as a child of a permission.');
        }

        if ($this->detectLoop($parent, $child)) {
            throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
        }

        $this->db->createCommand()->insert($this->itemChildTable, [
            'app_id' => $this->appId,
            'parent' => $parent->name,
            'child' => $child->name,
        ])->execute();

        $this->invalidateCache();

        return true;
    }

    /**
     * @param Item $parent
     * @param Item $child
     * @return bool
     * @throws \yii\db\Exception
     */
    public function removeChild($parent, $child)
    {
        $result = $this->db->createCommand()->delete($this->itemChildTable, [
                'app_id' => $this->appId,
                'parent' => $parent->name,
                'child' => $child->name,
            ])->execute() > 0;

        $this->invalidateCache();

        return $result;
    }

    /**
     * @param Item $parent
     * @return bool
     * @throws \yii\db\Exception
     */
    public function removeChildren($parent)
    {
        $result = $this->db->createCommand()->delete($this->itemChildTable, [
                'app_id' => $this->appId,
                'parent' => $parent->name,
            ])->execute() > 0;

        $this->invalidateCache();

        return $result;
    }

    /**
     * @param Item $parent
     * @param Item $child
     * @return bool
     */
    public function hasChild($parent, $child)
    {
        return (new Query())->from($this->itemChildTable)->where([
                'app_id' => $this->appId,
                'parent' => $parent->name,
                'child' => $child->name,
            ])->one($this->db) !== false;
    }

    /**
     * @param string $name
     * @return array|Item[]
     */
    public function getChildren($name)
    {
        $query = (new Query())->select([
            'name',
            'type',
            'description',
            'rule_name',
            'data',
            'created_at',
            'updated_at',
        ])->from(['a' => $this->itemTable, 'b' => $this->itemChildTable])->where([
            'a.app_id' => $this->appId,
            'b.app_id' => $this->appId,
            'parent' => $name,
            'name' => new Expression('[[child]]'),
        ]);

        $children = [];
        foreach ($query->all($this->db) as $row) {
            $children[$row['name']] = $this->populateItem($row);
        }

        return $children;
    }

    /**
     * @param \yii\rbac\Permission|Role $role
     * @param int|string $userId
     * @return Assignment
     * @throws \yii\db\Exception
     */
    public function assign($role, $userId)
    {
        $assignment = new Assignment([
            'userId' => $userId,
            'roleName' => $role->name,
            'createdAt' => time(),
        ]);

        $this->db->createCommand()->insert($this->assignmentTable, [
            'app_id' => $this->appId,
            'user_id' => $assignment->userId,
            'item_name' => $assignment->roleName,
            'created_at' => $assignment->createdAt,
        ])->execute();

        unset($this->checkAccessAssignments[(string)$userId]);

        $this->invalidateCache();

        return $assignment;
    }

    /**
     * @param \yii\rbac\Permission|Role $role
     * @param int|string $userId
     * @return bool
     * @throws \yii\db\Exception
     */
    public function revoke($role, $userId)
    {
        if ($this->isEmptyUserId($userId)) {
            return false;
        }

        unset($this->checkAccessAssignments[(string)$userId]);
        $result = $this->db->createCommand()->delete($this->assignmentTable, [
                'app_id' => $this->appId,
                'user_id' => (string)$userId,
                'item_name' => $role->name,
            ])->execute() > 0;

        $this->invalidateCache();

        return $result;
    }

    /**
     * @param mixed $userId
     * @return bool
     * @throws \yii\db\Exception
     */
    public function revokeAll($userId)
    {
        if ($this->isEmptyUserId($userId)) {
            return false;
        }

        unset($this->checkAccessAssignments[(string)$userId]);
        $result = $this->db->createCommand()->delete($this->assignmentTable, [
                'app_id' => $this->appId,
                'user_id' => (string)$userId,
            ])->execute() > 0;

        $this->invalidateCache();

        return $result;
    }

    /**
     * @throws \yii\db\Exception
     */
    public function removeAll()
    {
        $this->removeAllAssignments();
        $this->db->createCommand()->delete($this->itemChildTable, ['app_id' => $this->appId])->execute();
        $this->db->createCommand()->delete($this->itemTable, ['app_id' => $this->appId])->execute();
        $this->db->createCommand()->delete($this->ruleTable, ['app_id' => $this->appId])->execute();
        $this->invalidateCache();
    }

    /**
     * @throws \yii\db\Exception
     */
    public function removeAllPermissions()
    {
        $this->removeAllItems(Item::TYPE_PERMISSION);
    }

    /**
     * @throws \yii\db\Exception
     */
    public function removeAllRoles()
    {
        $this->removeAllItems(Item::TYPE_ROLE);
    }

    /**
     * @param $type
     * @throws \yii\db\Exception
     */
    protected function removeAllItems($type)
    {
        if (!$this->supportsCascadeUpdate()) {
            $names = (new Query())
                ->select(['name'])
                ->from($this->itemTable)
                ->where(['app_id' => $this->appId, 'type' => $type])
                ->column($this->db);
            if (empty($names)) {
                return;
            }
            $key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent';
            $this->db->createCommand()->delete($this->itemChildTable, [
                'app_id' => $this->appId,
                $key => $names,
            ])->execute();
            $this->db->createCommand()->delete($this->assignmentTable, [
                'app_id' => $this->appId,
                'item_name' => $names,
            ])->execute();
        }
        $this->db->createCommand()->delete($this->itemTable, [
            'app_id' => $this->appId,
            'type' => $type,
        ])->execute();

        $this->invalidateCache();
    }

    /**
     * @throws \yii\db\Exception
     */
    public function removeAllRules()
    {
        $this->db->createCommand()->update($this->itemTable, [
            'app_id' => $this->appId,
            'rule_name' => null,
        ])->execute();

        $this->db->createCommand()->delete($this->ruleTable, ['app_id' => $this->appId])->execute();

        $this->invalidateCache();
    }

    /**
     * @throws \yii\db\Exception
     */
    public function removeAllAssignments()
    {
        $this->checkAccessAssignments = [];
        $this->db->createCommand()->delete($this->assignmentTable, ['app_id' => $this->appId])->execute();
    }

    public function loadFromCache()
    {
        if ($this->items !== null || !$this->cache instanceof CacheInterface) {
            return;
        }

        $data = $this->cache->get($this->cacheKey);
        if (is_array($data) && isset($data[0], $data[1], $data[2])) {
            list($this->items, $this->rules, $this->parents) = $data;
            return;
        }

        $query = (new Query())->from($this->itemTable)->where(['app_id' => $this->appId]);
        $this->items = [];
        foreach ($query->all($this->db) as $row) {
            $this->items[$row['name']] = $this->populateItem($row);
        }

        $query = (new Query())->from($this->ruleTable)->where(['app_id' => $this->appId]);
        $this->rules = [];
        foreach ($query->all($this->db) as $row) {
            $data = $row['data'];
            if (is_resource($data)) {
                $data = stream_get_contents($data);
            }
            if ($data) {
                $this->rules[$row['name']] = unserialize($data);
            }
        }

        $query = (new Query())->from($this->itemChildTable)->where(['app_id' => $this->appId]);
        $this->parents = [];
        foreach ($query->all($this->db) as $row) {
            if (isset($this->items[$row['child']])) {
                $this->parents[$row['child']][] = $row['parent'];
            }
        }

        $this->cache->set($this->cacheKey, [$this->items, $this->rules, $this->parents]);
    }

    /**
     * @param string $roleName
     * @return array|string[]
     */
    public function getUserIdsByRole($roleName)
    {
        if (empty($roleName)) {
            return [];
        }

        return (new Query())->select('[[user_id]]')
            ->from($this->assignmentTable)
            ->where(['app_id' => $this->appId, 'item_name' => $roleName])->column($this->db);
    }

    /**
     * @param $userId
     * @return array|string
     */
    private function getUserRolesCacheKey($userId)
    {
        return [
            $this->cacheKey,
            $this->rolesCacheSuffix,
            $this->appId,
            $userId,
        ];
    }

    /**
     * @return array|string
     */
    private function getUserRolesCachedSetKey()
    {
        return [
            $this->cacheKey,
            $this->rolesCacheSuffix,
            $this->appId,
        ];
    }

    /**
     * @param $userId
     * @param $roles
     */
    private function cacheUserRolesData($userId, $roles)
    {
        $cachedUserIds = $this->cache->get($this->getUserRolesCachedSetKey());

        if ($cachedUserIds === false) {
            $cachedUserIds = [];
        }

        $cachedUserIds[] = $userId;

        $this->cache->set($this->getUserRolesCacheKey($userId), $roles);
        $this->cache->set($this->getUserRolesCachedSetKey(), $cachedUserIds);
    }
}